<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-tag"></i> 社区管理
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 搜索栏 -->
    <div class="container">
      <div class="handle-box">
        <!-- <el-input v-model="searchForm.communityId" placeholder="社区ID" class="handle-input mr10" clearable /> -->
        <el-input v-model="searchForm.moduleName" placeholder="社区名称" class="handle-input mr10" clearable />
        <el-select v-model="searchForm.forumCategory" placeholder="社区分类" class="handle-input mr10" clearable>
          <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <!-- <el-input v-model="searchForm.description" placeholder="简介" class="handle-input mr10" clearable /> -->
        <!-- <el-date-picker v-model="searchForm.createTime" type="date" placeholder="创建时间" class="handle-input mr10"
          clearable /> -->
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="showAddCommunity">新增社区</el-button>
      </div>

      <!-- 表格 -->
      <el-table :data="tableData" border class="table" ref="communityTable" header-cell-class-name="table-header">
        <el-table-column prop="id" label="社区ID" width="100" />
        <el-table-column prop="communityName" label="社区名称"  />
        <el-table-column prop="categoryId" label="分类ID"  />
        <el-table-column prop="categoryName" label="分类名称"  />
        <el-table-column prop="description" label="简介" >
          <template #default="scope">
            <div class="description-cell">
              {{ scope.row.description || '-' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="image" label="图片"  align="center">
          <template #default="scope">
            <el-image v-if="scope.row.image" :src="scope.row.image" style="width: 50px; height: 50px;" fit="cover"
              :preview-src-list="[scope.row.image]" preview-teleported />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" >
          <template #default="scope">
            {{ scope.row.createTime ? dateFormat(scope.row.createTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="scope">
            <el-button type="text" @click="showEditCommunity(scope.row)">编辑</el-button>
            <el-button type="text" class="red" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="pagination.total">
        </el-pagination>
      </div>
    </div>

    <!-- 新增/编辑社区弹窗 -->
    <el-dialog v-model="communityDialog.visible" :title="communityDialog.isEdit ? '编辑社区' : '新增社区'" width="600px">
      <el-form :model="communityDialog.form" :rules="communityRules" ref="communityForm" label-width="100px">
        <el-form-item label="社区名称" prop="communityName">
          <el-input v-model="communityDialog.form.communityName" placeholder="请输入社区名称" />
        </el-form-item>
        <el-form-item label="社区分类" prop="categoryId">
          <div class="category-selector">
            <el-input v-model="selectedCategoryDisplay" placeholder="请选择社区分类" readonly />
            <el-button type="primary" @click="showCategorySelector">选择分类</el-button>
          </div>
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input v-model="communityDialog.form.description" type="textarea" :rows="4" placeholder="请输入社区简介" />
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <MediaUploader v-model="communityDialog.form.imageList" :limit="1" accept-type="image" />
          <div class="form-tip">请上传社区图片，建议尺寸为200x200像素</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="communityDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveCommunity">保存</el-button>
      </template>
    </el-dialog>

    <!-- 社区分类选择弹窗 -->
    <selectCommunityClass v-model="categorySelector.visible" :selectedData="categorySelector.selectedData"
      @confirm="handleCategoryConfirm" />
  </div>
</template>

<script>
import moment from "moment";
import { getCommunities, addCommunity, updateCommunity, deleteCommunity, getForumCategories } from "@/api/content";
import selectCommunityClass from "@/components/selectCommunityClass.vue";
import MediaUploader from "@/components/mediaUploader.vue";

export default {
  name: "CommunityManagement",
  components: {
    selectCommunityClass,
    MediaUploader
  },
  data() {
    return {
      searchForm: {
        communityId: "",
        forumCategory: "",
        moduleName: "",
        description: "",
        createTime: "",
      },
      tableData: [],
      // 社区分类列表
      categoryOptions: [],
      // 分页相关
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      // 社区弹窗
      communityDialog: {
        visible: false,
        isEdit: false,
        editId: null,
        form: {
          communityName: "",
          categoryId: "",
          description: "",
          imageList: [], // 使用数组存储图片
        },
      },
      // 分类选择器
      categorySelector: {
        visible: false,
        selectedData: null
      },

      // 表单验证规则
      communityRules: {
        communityName: [
          { required: true, message: '请输入社区名称', trigger: 'blur' },
          { min: 1, max: 50, message: '社区名称长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择社区分类', trigger: 'change' }
        ],
        description: [
          { max: 500, message: '简介不能超过500个字符', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    selectedCategoryDisplay() {
      if (this.categorySelector.selectedData) {
        return `${this.categorySelector.selectedData.categoryName} (ID: ${this.categorySelector.selectedData.id})`;
      }
      return '';
    }
  },
  mounted() {
    this.getForumCategoriesList();
    this.getData();
  },
  methods: {
    dateFormat(val) {
      return val ? moment(val).format("YYYY-MM-DD HH:mm:ss") : "";
    },
    handleSearch() {
      this.pagination.currentPage = 1;
      this.getData();
    },
    // 分页相关方法
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1;
      this.getData();
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.getData();
    },
    buildSearchParams() {
      const params = {
        limit: this.pagination.pageSize,
        offset: this.pagination.currentPage
      };

      if (this.searchForm.communityId) {
        params.id = this.searchForm.communityId;
      }
      if (this.searchForm.moduleName) {
        params.moduleName = this.searchForm.moduleName;
      }
      if (this.searchForm.forumCategory) {
        params.forumCategory = this.searchForm.forumCategory;
      }
      if (this.searchForm.description) {
        params.moduleBlurb = this.searchForm.description;
      }
      if (this.searchForm.createTime) {
        params.createTime = moment(this.searchForm.createTime).format('YYYY-MM-DD');
      }

      return params;
    },
    async getData() {
      try {
        const params = this.buildSearchParams();
        const response = await getCommunities(params);

        if (response && response.data) {
          // 根据接口字段映射数据
          this.tableData = (response.data.rows || response.data).map(item => ({
            id: item.id,
            communityName: item.moduleName || '',
            categoryId: item.forumCategory || '',
            categoryName: item.forumCategoryName || '',
            description: item.moduleBlurb || '',
            image: item.moduleImgUrl || '',
            createTime: item.createTime,
            updateTime: item.updateTime,
            // 保留原始数据用于编辑
            _original: item
          }));

          if (response.data.total !== undefined) {
            this.pagination.total = response.data.total;
          }
        }
      } catch (error) {
        console.error('获取社区数据失败:', error);
        this.$message.error('获取社区数据失败');
      }
    },
    showAddCommunity() {
      this.communityDialog.visible = true;
      this.communityDialog.isEdit = false;
      this.communityDialog.editId = null;
      this.communityDialog.form = {
        communityName: "",
        categoryId: "",
        description: "",
        imageList: [],
      };
      this.categorySelector.selectedData = null;
      this.$nextTick(() => {
        this.$refs.communityForm?.clearValidate();
      });
    },
    showEditCommunity(row) {
      this.communityDialog.visible = true;
      this.communityDialog.isEdit = true;
      this.communityDialog.editId = row.id;
      this.communityDialog.form = {
        communityName: row.communityName || "",
        categoryId: row.categoryId || "",
        description: row.description || "",
        imageList: row.image ? [{
          url: row.image,
          type: 'image/jpeg',
          name: 'community.jpg'
        }] : [],
      };
      // 设置已选择的分类数据
      this.categorySelector.selectedData = {
        id: row.categoryId,
        categoryName: row.categoryName
      };
      this.$nextTick(() => {
        this.$refs.communityForm?.clearValidate();
      });
    },
    showCategorySelector() {
      this.categorySelector.visible = true;
    },
    handleCategoryConfirm(categoryData) {
      this.categorySelector.selectedData = categoryData;
      this.communityDialog.form.categoryId = categoryData.id;
    },

    saveCommunity() {
      this.$refs.communityForm.validate(async (valid) => {
        if (valid) {
          try {
            // 将表单字段映射到接口字段
            const params = {
              moduleName: this.communityDialog.form.communityName, // 社区名称
              forumCategory: this.communityDialog.form.categoryId, // 分类ID
              forumCategoryName: this.categorySelector.selectedData ? this.categorySelector.selectedData.categoryName : '', // 分类名称
              moduleBlurb: this.communityDialog.form.description, // 简介
              moduleImgUrl: this.communityDialog.form.imageList.length > 0 ? this.communityDialog.form.imageList[0].url : '', // 图片
            };

            if (this.communityDialog.isEdit) {
              params.id = this.communityDialog.editId;
              await updateCommunity(params);
              this.$message.success('编辑社区成功');
            } else {
              await addCommunity(params);
              this.$message.success('新增社区成功');
            }

            this.communityDialog.visible = false;
            this.getData();
          } catch (error) {
            console.error('保存社区失败:', error);
            this.$message.error('保存社区失败');
          }
        }
      });
    },
    handleDelete(row) {
      this.$confirm(`确定要删除社区"${row.communityName}"吗？`, "提示", {
        type: "warning"
      }).then(async () => {
        try {
          await deleteCommunity({ id: row.id });
          this.$message.success('删除社区成功');
          this.getData();
        } catch (error) {
          console.error('删除社区失败:', error);
          this.$message.error('删除社区失败');
        }
      }).catch(() => {
        // 用户取消删除
      });
    },
    // 获取社区分类列表
    async getForumCategoriesList() {
      try {
        const response = await getForumCategories({ limit: 1000, offset: 1 });
        if (response && response.data) {
          this.categoryOptions = (response.data.rows || response.data).map(item => ({
            value: item.id,
            label: item.categoryName || item.name,
            id: item.id,
            categoryName: item.categoryName || item.name
          }));
        }
      } catch (error) {
        console.error('获取社区分类列表失败:', error);
        this.$message.error('获取社区分类列表失败');
      }
    },
  },
};
</script>

<style lang='scss' scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 200px;
  display: inline-block;
}

.handle-input.el-select {
  width: 200px;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.description-cell {
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  line-height: 20px;
}

.category-selector {
  display: flex;
  gap: 10px;
  align-items: center;

  .el-input {
    flex: 1;
  }
}

.form-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

::v-deep .el-date-editor {
  margin-right: 10px;
  width: 200px;
}
</style>